<?php

namespace Redis;

class RedisLock { // class start

    private $_config;
    private $_redis;

    /**
     * ��ʼ��
     * @param Array $config redis�����趨
     */
    public function __construct($config = array()) {
        $this->_config = $config;
        if (!is_array($this->_config) || !isset($this->_config['host'])) {
            $this->_config = array(
                'host' => 'localhost',
                'port' => 6379,
                'index' => 0,
                'auth' => '',
                'timeout' => 1,
                'reserved' => NULL,
                'retry_interval' => 100,
            );
        }
        $this->_redis = $this->connect();
    }

    /**
     * ��ȡ��
     * @param  String  $key    ����ʶ
     * @param  Int     $expire ������ʱ��
     * @return Boolean
     */
    public function lock($key, $expire = 5) {
        $is_lock = $this->_redis->setnx($key, time() + $expire);

        // ���ܻ�ȡ��
        if (!$is_lock) {

            // �ж����Ƿ����
            $lock_time = $this->_redis->get($key);

            // ���ѹ��ڣ�ɾ���������»�ȡ
            if (time() > $lock_time) {
                $this->unlock($key);
                $is_lock = $this->_redis->setnx($key, time() + $expire);
            }
        }

        return $is_lock ? true : false;
    }

    /**
     * �ͷ���
     * @param  String  $key ����ʶ
     * @return Boolean
     */
    public function unlock($key) {
        echo "解锁了";
        return $this->_redis->del($key);
    }

    /**
     * ����redis����
     * @return Link
     */
    private function connect() {
        try {
            $redis = new \Redis();
            $redis->connect($this->_config['host'], $this->_config['port'], $this->_config['timeout']);
            if (empty($this->_config['auth'])) {
                $redis->auth($this->_config['auth']);
            }
            $redis->select($this->_config['index']);
        } catch (RedisException $e) {
            throw new Exception($e->getMessage());
            return false;
        }
        return $redis;
    }

}

?>